package orgInfo

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
	"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

// 用户（普通用户、管理员）通道操作---执行交易
//   从Application结构体中搬过来
//   暂时只有：调用链码（调用链码中的函数 包含了上传数据）、查询数据

func (o *OrgInfo) ChaincodeInvoke(fabSDK *fabsdk.FabricSDK, channelID string, userName string, chaincodeID string, fcn string, args []string) (*channel.Response, error) {
	// 获取chClient
	chClient, err := o.CreatChannelClient(fabSDK, channelID, userName)
	if err != nil {
		return nil, fmt.Errorf("ChaincodeInvoke err: %v", err)
	}
	// 将参数转换为[][]byte
	var argsbyte [][]byte
	for _, arg := range args {
		argsbyte = append(argsbyte, []byte(arg))
	}
	req := channel.Request{
		ChaincodeID: chaincodeID,
		Fcn:         fcn,
		Args:        argsbyte,
	}
	resp, err := chClient.Execute(req)
	if err != nil {
		return nil, fmt.Errorf("ChaincodeInvoke err: %v", err)
	}
	return &resp, nil
}

// InitCC 初始化链码
func (o *OrgInfo) InitCC(fabSDK *fabsdk.FabricSDK, channelID string, userName string, chaincodeID string, initFcn string) error {
	// 获取chClient
	chClient, err := o.CreatChannelClient(fabSDK, channelID, userName)
	if err != nil {
		return fmt.Errorf("ChaincodeInvoke err: %v", err)
	}
	request := channel.Request{
		ChaincodeID: chaincodeID,
		Fcn:         initFcn,
		Args:        nil,
		IsInit:      true,
	}
	_, err = chClient.Execute(request, channel.WithRetry(retry.DefaultChannelOpts))
	if err != nil {
		return fmt.Errorf("链码初始化失败: %v", err)
	}
	return nil
}

// ChaincodeQuery 查询链码
func (o *OrgInfo) ChaincodeQuery(fabSDK *fabsdk.FabricSDK, channelID string, userName string, chaincodeID string, fcn string, args []string) (*channel.Response, error) {
	// 获取chClient
	chClient, err := o.CreatChannelClient(fabSDK, channelID, userName)
	if err != nil {
		return nil, fmt.Errorf("ChaincodeQuery err: %v", err)
	}
	// 将参数转换为[][]byte
	var argsbyte [][]byte
	for _, arg := range args {
		argsbyte = append(argsbyte, []byte(arg))
	}
	req := channel.Request{
		ChaincodeID: chaincodeID,
		Fcn:         fcn,
		Args:        argsbyte,
	}
	resp, err := chClient.Query(req)
	if err != nil {
		return nil, fmt.Errorf("ChaincodeQuery err: %v", err)
	}
	return &resp, nil

}
